package com.zeny.coding.service.impl;

import com.zeny.coding.constants.EmailMessageConstant;
import com.zeny.coding.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <h2>TODO</h2>
 *
 * @Author Zeny
 */
@Slf4j
@SuppressWarnings("all")
@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSenderImpl sender;

    @Override
    public void sendEmail(String email, String code) throws Exception{
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(()->{
            try {
                String text = String.format(EmailMessageConstant.TEXT, code);
                MimeMessage message = sender.createMimeMessage();
                MimeMessageHelper messageHelper = new MimeMessageHelper(message);
                messageHelper.setSubject(EmailMessageConstant.SUBJECT);
                messageHelper.setFrom(EmailMessageConstant.FROM);
                messageHelper.setTo(email);
                messageHelper.setText(text, true);
                sender.send(message);
                log.info("EmailServiceImpl sendEmail 发送短信成功, 验证码: {}", code);
            }catch (Exception e) {
               log.error("发送短信给: {} 异常, 错误信息: ", email, e.getMessage());
            }
        });
        executor.shutdown();
    }
}
